package encrypt

import (
	"bytes"
	"crypto/md5"
	"encoding/base64"
	"encoding/hex"
	"regexp"
	"strings"

	"github.com/gin-gonic/gin"
)

func Md5Encrypt(s string) string {
	var buffer bytes.Buffer
	buffer.WriteString(s)
	buffer.WriteString(s[1:])
	h := md5.New()
	h.Write([]byte(buffer.String()))
	m := h.Sum(nil)

	return hex.EncodeToString(m)
}

func CheckMd5Encrypt(s string, pwd string) bool {
	return Md5Encrypt(s) == pwd
}

func Encrypt(str string, t int, key string) string {
	if t == 2 {
		decode, err := base64.StdEncoding.DecodeString(str)
		if err != nil {
			panic(err)
		}

		str = string(decode)
	}

	gin.DefaultWriter.Write([]byte("authkey:" + key + "\n"))

	h := md5.New()
	h.Write([]byte(key))

	authKey := hex.EncodeToString(h.Sum(nil))

	authKeyLen := len(authKey)
	strLen := len(str)
	gin.DefaultWriter.Write([]byte("str:" + str + "\n"))
	gin.DefaultWriter.Write([]byte("authkey:" + authKey + "\n"))
	first := []byte(str)[0] ^ []byte(authKey)[0]
	s := string(first)

	if t == 2 {
		first = []byte(str)[0]
	}

	for i := 1; i < strLen; i++ {
		tmp := []byte(str)[i] ^ []byte(authKey)[(i+int(first))%authKeyLen]
		s += string(tmp)
	}

	if t == 1 {
		return replaceEqual(base64.StdEncoding.EncodeToString([]byte(s)))
	}

	return s
}

func MacCheck(str string) bool {
	pat := `^[A-F0-9]{2}([-:][A-F0-9]{2}){5}$`
	res, _ := regexp.MatchString(pat, str)
	return res
}

func replaceEqual(str string) string {
	return strings.Replace(str, "=", "", -1)
}
